package org.example.rowing.service;

import lombok.extern.slf4j.Slf4j;
import org.example.rowing.domain.*;
import org.example.rowing.mapper.*;
import org.example.rowing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ResultInfoService {

    @Autowired
    private EventResultMapper eventResultMapper;
    @Autowired
    private RaceInfoService raceInfoService;

    public void saveOrUpdateEventResult(EventResult eventResult) {
        if (eventResult.getId() == null) {
            eventResultMapper.insertEventResult(eventResult);
            log.info("新赛事结果数据已保存: {}", eventResult);
        } else {
            eventResultMapper.updateEventResult(eventResult);
            log.info("赛事结果数据已更新: {}", eventResult);
        }
    }

    public List<EventResult> showSearchedEventResults(EventResult eventResultCondition) {
        List<EventResult> eventResults = new ArrayList<>();
        if (eventResultCondition != null) {
            eventResults = eventResultMapper.selectEventResultByCondition(eventResultCondition);
        }
        return eventResults;
    }

    public List<GoldRankingVO> showSearchedGoldRankings(EventResultVO eventResultVOCondition) {
        List<GoldRankingVO> goldRankingVOS = new ArrayList<>();
        List<EventResultVO> eventResultVOS = eventResultMapper.selectEventResultVOByCondition(eventResultVOCondition);
        for (EventResultVO eventResultVO : eventResultVOS) {
            GoldRankingVO goldRankingVO = new GoldRankingVO(eventResultVO.getId(), eventResultVO.getEvent(), eventResultVO.getTeam(), eventResultVO.getGoldMedal());
            goldRankingVOS.add(goldRankingVO);
        }
        // 按金牌数降序排序
        goldRankingVOS.sort((m1, m2) -> Integer.compare(m2.getGoldCount(), m1.getGoldCount()));

        int rank = 0;      // 当前分配的排名
        int realRank = 0;  // 实际迭代次数，用于处理并列排名后顺延
        int prevGoldMedal = -1; // 上一条记录的金牌数

        for (GoldRankingVO goldRankingVO : goldRankingVOS) {
            realRank++;
            // 若当前记录金牌数与上一条不同，则更新排名为当前实际排名
            if (goldRankingVO.getGoldCount() != prevGoldMedal) {
                rank = realRank;
                prevGoldMedal = goldRankingVO.getGoldCount();
            }
            goldRankingVO.setGoldRank(rank);
        }
        return goldRankingVOS;
    }

    public List<MedalRankingVO> showSearchedMedalRankings(EventResultVO eventResultVOCondition) {
        List<MedalRankingVO> medalRankingVOS = new ArrayList<>();
        List<EventResultVO> eventResultVOS = eventResultMapper.selectEventResultVOByCondition(eventResultVOCondition);
        for (EventResultVO eventResultVO : eventResultVOS) {
            MedalRankingVO medalRankingVO = new MedalRankingVO(eventResultVO.getId(), eventResultVO.getEvent(), eventResultVO.getTeam(),
                    eventResultVO.getGoldMedal(), eventResultVO.getSilverMedal(),
                    eventResultVO.getBronzeMedal(), eventResultVO.getTotalMedal());
            medalRankingVOS.add(medalRankingVO);
        }
        // 按奖牌总数降序排序
        medalRankingVOS.sort((m1, m2) -> Integer.compare(m2.getTotalCount(), m1.getTotalCount()));

        int rank = 0;      // 当前分配的排名
        int realRank = 0;  // 实际迭代次数，用于处理并列排名后顺延
        int prevTotalMedal = -1; // 上一条记录的奖牌数

        for (MedalRankingVO medalRankingVO : medalRankingVOS) {
            realRank++;
            // 若当前记录金牌数与上一条不同，则更新排名为当前实际排名
            if (medalRankingVO.getTotalCount() != prevTotalMedal) {
                rank = realRank;
                prevTotalMedal = medalRankingVO.getTotalCount();
            }
            medalRankingVO.setMedalRank(rank);
        }
        return medalRankingVOS;
    }

    public List<ScoreRankingVO> showSearchedScoreRankings(EventResultVO eventResultVOCondition) {
        List<ScoreRankingVO> scoreRankingVOS = new ArrayList<>();
        List<EventResultVO> eventResultVOS = eventResultMapper.selectEventResultVOByCondition(eventResultVOCondition);
        for (EventResultVO eventResultVO : eventResultVOS) {
            ScoreRankingVO scoreRankingVO = new ScoreRankingVO(eventResultVO.getId(), eventResultVO.getEvent(), eventResultVO.getTeam(), eventResultVO.getTotalScore());
            scoreRankingVOS.add(scoreRankingVO);
        }
        // 按积分总数降序排序
        scoreRankingVOS.sort((m1, m2) -> Integer.compare(m2.getTotalScore(), m1.getTotalScore()));

        int rank = 0;      // 当前分配的排名
        int realRank = 0;  // 实际迭代次数，用于处理并列排名后顺延
        int prevTotalScore = -1; // 上一条记录的奖牌数

        for (ScoreRankingVO scoreRankingVO : scoreRankingVOS) {
            realRank++;
            // 若当前记录金牌数与上一条不同，则更新排名为当前实际排名
            if (scoreRankingVO.getTotalScore() != prevTotalScore) {
                rank = realRank;
                prevTotalScore = scoreRankingVO.getTotalScore();
            }
            scoreRankingVO.setScoreRank(rank);
        }
        return scoreRankingVOS;
    }

    public List<RoundScoreVO> showSearchedRoundScoreRanking(RoundScoreVO roundScoreCondition) {
        List<RoundScoreVO> roundScoreVOList = new ArrayList<>();
        List<RoundScoreVO> roundScoreVOS = raceInfoService.showRoundScoreByCondition(roundScoreCondition);
        log.info("目前查询到{}条轮次信息", roundScoreVOS.size());

        // 如果任一RoundResult的score为null，则直接返回空列表
        if (roundScoreVOS.stream().anyMatch(r -> r.getScore() == null)) {
            return roundScoreVOList;
        }

        // 先按赛道名称中提取的组别进行分组
        Map<String, List<RoundScoreVO>> groupedByGroup = roundScoreVOS.stream()
                .collect(Collectors.groupingBy(m -> extractGroup(m.getLane())));

        for (Map.Entry<String, List<RoundScoreVO>> entry : groupedByGroup.entrySet()) {
            List<RoundScoreVO> groupList = entry.getValue();
            // 按比赛用时升序排序
            groupList.sort(Comparator.comparingDouble(RoundScoreVO::getScore));
            int rank = 0;      // 当前分配的排名
            int realRank = 0;  // 实际迭代次数，用于处理并列排名后顺延
            double prevRoundResult = -1; // 上一条记录的金牌数

            for (RoundScoreVO roundScoreVO : groupList) {
                realRank++;
                // 若当前记录金牌数与上一条不同，则更新排名为当前实际排名
                if (roundScoreVO.getScore() != prevRoundResult) {
                    rank = realRank;
                    prevRoundResult = roundScoreVO.getScore();
                }
                roundScoreVO.setRank(rank);
                roundScoreVOList.add(roundScoreVO);
            }
        }
        return roundScoreVOList;
    }

    /**
     * 根据赛道名称提取组信息。
     * 例如：对于 "A组3号赛道"，返回 "A组"
     */
    private String extractGroup(String laneName) {
        if (laneName != null && laneName.contains("组")) {
            int index = laneName.indexOf("组");
            return laneName.substring(0, index + 1);
        }
        return "未知组";
    }
}
